#include <rtthread.h>
#include <board.h>
#include <rthw.h>
#include "rtdevice.h"

#define RT_SERIAL_CONFIG_USER              \
{                                          \
    BAUD_RATE_115200, /* 115200 bits/s */  \
    DATA_BITS_8,      /* 8 databits */     \
    STOP_BITS_1,      /* 1 stopbit */      \
    PARITY_NONE,      /* No parity  */     \
    BIT_ORDER_LSB,    /* LSB first sent */ \
    NRZ_NORMAL,       /* Normal mode */    \
    RT_SERIAL_FIFO_BUFSZ, /* Buffer size */  \
    0                                      \
}

rt_thread_t uart_tid = RT_NULL;

void uart_test_thread(void *parameter)
{
    rt_device_t uart_dev;
    rt_uint8_t *recvbuf = RT_NULL, buf[10] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', };
    rt_size_t rcv_off = 0, recv_sz = 0, tmp = 0;
    struct serial_configure uart_conf = RT_SERIAL_CONFIG_USER;

    uart_dev = rt_device_find("uart1");
    if (uart_dev == RT_NULL) {
        rt_kprintf("Find device: %s failed\n", "uart1");
        return;
    }
    rt_device_control(uart_dev, RT_DEVICE_CTRL_CONFIG, &uart_conf);
    if (rt_device_open(uart_dev, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_STREAM
                               | RT_DEVICE_FLAG_INT_RX
                               | RT_DEVICE_FLAG_INT_TX
                               | RT_DEVICE_OFLAG_BLOCKING) != RT_EOK)
    {
        rt_kprintf("Open device: %s failed\n", "uart1");
        return;
    }
    recvbuf = rt_malloc(512);
//    rt_memset(recvbuf, 0x5A, 512);
    for (tmp = 0; tmp < 512; tmp++) {
        recvbuf[tmp] = '0' + (tmp % 10);
    }
//    recvbuf[11] = '\n';
#define UART_RW_TEST
    while (1) {
#if defined(UART_WRITE_TEST)
        rt_device_write(uart_dev, 0, recvbuf, 510);
        rt_thread_mdelay(100);
#elif defined(UART_READ_TEST)
        recv_sz = rt_device_read(uart_dev, -1, recvbuf, 512);
        rt_thread_delay(2);
#elif defined(UART_RW_TEST)
        recv_sz = rt_device_read(uart_dev, -1, recvbuf, 512);
        if (recv_sz > 0) {
            recvbuf[recv_sz] = 0;
//            rt_kprintf("[%d]:%s\n", recv_sz, recvbuf);
            rt_device_write(uart_dev, 0, recvbuf, recv_sz);
        }
        rt_thread_delay(2);
#endif
    }
}

int uart_test_init(void)
{
    uart_tid = rt_thread_create("uartT",              
                           uart_test_thread, RT_NULL,
                           2048,
                           0,
                           20);
    if (uart_tid != RT_NULL)
        rt_thread_startup(uart_tid);

    return 0;
}
INIT_APP_EXPORT(uart_test_init);
